#!/usr/bin/python
# vim:fileencoding=utf-8:sw=4:et
# Install build depends found in a debian/control file

from __future__ import print_function, unicode_literals, absolute_import
import sys, os, io
import logging as log

__version__ = "0.1"
CONTROL_FNAME = "control"

def parse_control_file(fname):
    """Parse debian control file
    @return: a list of dict for each package in the control file
    """
    control = []
    with io.open(fname, encoding="UTF-8") as fd:
        val = None
        item = {}
        control.append(item)

        for n, line in enumerate(fd):
            if line.isspace(): # new package seperator
                item = {}
                control.append(item)
            elif line[0] in {" ", "\t"}: # continues for a tag
                val.append(line)
            else:
                k, s, v = line.partition(":")
                if s:
                    val = []
                    item[k.strip()] = val
                    val.append(v)
                else:
                    log.error("Control file invalid line [{}]: {}".format(
                        n+1, line.strip()))
                    log.error('No ":" in the tag line')
                    return []

    # join value list into a string
    control2 = []
    for p in control:
        if len(p) > 0:
            item = {}
            control2.append(item)
            for k, v in p.items():
                item[k] = "".join(v)

    # dump controls
    #[print("%s=>%s"%(k,v),end="") for p in control2 for k,v in p.items()]
    return control2

def guess_control_file():
    """Find the debian control file under current directory """
    debian_dir = "debian"
    ret = ""
    if os.path.exists(debian_dir):
        ret = os.path.join(debian_dir, CONTROL_FNAME)
        if not os.path.exists(ret):
            ret = ""
    if len(ret) == 0:
        if os.path.exists(CONTROL_FNAME):
            ret = CONTROL_FNAME
    return ret

def collect_build_depends(control_list):
    """Get all the depend packages on a control struct"""
    deps = []
    for p in control_list:
        for k in p.keys():
            if k.lower() in {"build-depends", "build-depends-indep"}:
                ds = [x.strip() for x in p[k].split(",")]
                deps.extend(ds)
    log.debug(deps)
    return deps

def install_depends(deps):
    """Install a list of depend packages"""
    import subprocess
    pure_depends = [x.split()[0] for x in deps]
    cmd = ["/usr/bin/aptitude", "install"] + pure_depends
    print(" ".join(cmd))
    ret = subprocess.call(cmd)
    return ret

def setup_arg_parser():
    import argparse
    parser = argparse.ArgumentParser(
            description="Install build depends for debian control file")
    parser.add_argument("control_file", nargs="?", help="a debian control file")
    parser.add_argument("-D", "--debug", action="store_true",
            help="debug run")
    return parser

def main():
    parser = setup_arg_parser()
    args = parser.parse_args()

    log_level = log.INFO
    if args.debug == True:
        log_level = log.DEBUG
    log.basicConfig(format="%(levelname)s>> %(message)s", level=log_level)

    if args.control_file is not None:
        fname = args.control_file
    else:
        fname = guess_control_file()
    if len(fname) == 0 or not os.path.exists(fname):
        log.error('Failed to find a debian "control" file.')
        return 2
    log.info('Use control file: {}'.format(fname))

    control = parse_control_file(fname)
    depends = collect_build_depends(control)
    if len(depends) < 1:
        log.error("No depends found in the control file.")
        return 1
    depends.insert(0, "build-essential")
    ret = install_depends(depends)

    # return ret

    # Print extra compilation info
    packages = ["libfontforge1", "libgdraw4", "fontforge",
            "python-fontforge", "fontforge-dbg"]
    if ret == 0 or args.debug:
        print(
"""Now as a normal user, you can compile fontforge by doing:

    ./bootstrap
    ./configure
    make -j

then run it:

    ./fontforgeexe/fontforge

or install it:

    make install

If you want to make debian FontForge packages, as a normal user, do:

    ./bootstrap
    dpkg-buildpackage -rfakeroot -b

Then install packages "{}" in *parent* directory, as root, by doing:

    cd ..
    ls *.deb
    dpkg -i package-name1.deb package-name2.deb ...
""".format('", "'.join(packages)))
    return ret

if __name__ == '__main__':
    ret = main()
    sys.exit(ret)

